<template>
	<view>
		<SkuPopup
			:show="show"
			:skuInfo="skuInfo"
			:list="productSkus"
			:bgColor="activeBackgroundColor"
			:goodsName="goods.name"
			@checkSku="checkSku"
			@priceChange="goodsPriceChange"
			@goodsNumChange="goodsNumChange"
			@addCart="addCart"
			@close="close"
		></SkuPopup>
		<CartListPopup
			:show="listShow"
			:list="cartList"
			:goodsKeys="goodsKeys"
			@close="cartPopupClose(false)"
			@del="cartPopupClose(true)"
			@delGoods="delCartGoods"
			@goodsNumChange="cartGoodsNumChange"
		></CartListPopup>
	</view>
</template>

<script>
import { getStoreCart, postAddStoreCart, postDelStoreCart, postDelStoreCartItem, postEditStoreCart,getGoodsSkuDetail } from '@/common/request/api';

import SkuPopup from '../../child/skuPopup.vue'
import CartListPopup from '../../child/cartList.vue'
export default {
	props: {
		primary: String,
		listShow: Boolean,
		isPay: Boolean,
		storeId: String,
		isShow:Boolean
	},
	components: {
		SkuPopup,
		CartListPopup
	},
	data() {
		return {
			show: false,
			goods: {},
			skuIds: [],
			skuInfo: {},
			productSkus: [],
			productSkuSpecifications: [],
			// 商品sku缓存
			goodsSkuMap: new Map([]),
			// 缓存已加入购物车的商品map。key是商品的skuid,value是对应的商品
			checkGoodsMap: new Map([]),
			productAll: 0,
			goodsPrice: 0,
			cartList: [],
			goodsKeys: {
				image: 'params.sku.skuCoverImg',
				skuName: 'params.sku.skuSpec',
				price: 'params.sku.price',
				name: 'params.sku.productName',
				qry: 'basketCount'
			}
		}
	},
	computed: {
		activeBackgroundColor() {
			return this.primary.replace('1)', '0.05)')
		}
	},
	watch: {
		isShow (val) {
			if(val){
				this.$emit('setShow',false)
				this.getShoppingCart()
				
			}
			
		},
		isPay(val) {
			if (val) {
				this.pay()
				this.$emit('closePay')
			}
		}
	},
	created() {
		this.getShoppingCart()
		this.$emit('setShow',false)
	},
	methods: {
		getShoppingCart() {
			if (!this.storeId) return
			getStoreCart(this.storeId).then(res => {
		
				
					this.cartList = res.data
					this.checkGoodsMap = new Map([])
					let price = 0
					res.data.forEach(item => {
						price = this.$accAdd(price, this.$accMul(item.params.sku.price, item.basketCount))
						this.checkGoodsMap.set(item.skuId, item)
					})
					this.goodsPrice = price
					this.productAll = res.productAll
					this.$emit('cartChange', price, res.productAll)
				
	
			})
		},
		getSku(goods) {
			uni.showLoading({
				title: 'loading....'
			})
			if (this.goodsSkuMap.has(goods.id)) {
				this.openSkuPopup(this.getSkuGoodsNumber(this.goodsSkuMap.get(goods.id)), goods)
				uni.hideLoading()
			} else {
				getGoodsSkuDetail({ productId: goods.id })
					.then(res => {
						if (res.code === 200) {
							let data = this.getSkuGoodsNumber(res.data)

							this.goodsSkuMap.set(goods.id, data)
							this.openSkuPopup(data, goods)
						}
					})
					.finally(() => uni.hideLoading())
			}
		},
		getSkuGoodsNumber(data) {
			data.productSkuSpecifications = data.productSkuSpecifications.map(item => {
				if (this.checkGoodsMap.has(item.id)) {
					item['_goodsNum'] = this.checkGoodsMap.get(item.id).basketCount
				}
				return item
			})
			return data
		},
		openSkuPopup(data, goods) {
			this.productSkuSpecifications = data.productSkuSpecifications
			// 如果当前商品的sku有已经加入购物车的，则选择最靠前的已加入购物车的sku作为默认展示，没有则选择第零位
			let sku = this.productSkuSpecifications.find(item => item['_goodsNum']) || this.productSkuSpecifications[0]
			sku['goodsNum'] = sku['_goodsNum'] || 0
			// 添加sku对应的商品id，方便在购物车列表中修改goodsSkuMap对应的商品sku的数量
			sku._goodsId = goods.id
			this.skuInfo = sku

			this.skuIds = this.skuInfo.skuKey.split('/')
			this.productSkus = data.productSkus.map((item, index) => {
				item.productSkuValues.forEach(items => {
					items.isCheck = items.id == this.skuIds[index]
				})
				return item
			})
			this.goods = goods
			this.show = true
		},
		checkSku(index, sindex) {
			this.productSkus[index].productSkuValues.forEach((item, indexs) => {
				item.isCheck = indexs === sindex
			})
			this.productSkus.forEach((item, i) => {
				item.productSkuValues.forEach(sitem => {
					if (sitem.isCheck) {
						this.skuIds[i] = sitem.id
					}
				})
			})
			// 选择的sku与商品的productSkus长度相同，则代表商品的每个规格都有选中
			if (this.skuIds.length == this.productSkus.length && !this.skuIds.includes(undefined)) {
				let sku = this.productSkuSpecifications.find(item => item.skuKey == this.skuIds.join('/'))
				if (this.checkGoodsMap.has(sku.id)) {
					sku['goodsNum'] = this.checkGoodsMap.get(sku.id).basketCount
				}
				sku._goodsId = this.goods.id
				this.skuInfo = sku
			}
		},
		addCart(basketCount) {
			let sku = this.productSkuSpecifications.find(item => item.skuKey == this.skuIds.join('/'))
			postAddStoreCart({
				skuId: sku.id,
				basketCount
			}).then(res => {
				this.getShoppingCart()
			})
		},
		goodsPriceChange(type) {
			let price = type ? this.skuInfo.price : -this.skuInfo.price
			let num = type ? 1 : -1
			this.goodsPrice = this.$accAdd(this.goodsPrice, price)
			this.productAll += num
			this.$emit('cartChange', this.goodsPrice, this.productAll)
			// this.$forceUpdate()
		},
		goodsNumChange(basketCount) {
			let sku = this.productSkuSpecifications.find(item => item.skuKey == this.skuIds.join('/'))
			if (basketCount === 0) {
				postDelStoreCartItem(sku.id).then(res => {
					if (res.code === 200) {
						this.getShoppingCart()
					}
				})
			} else {
				postEditStoreCart({
					skuId: sku.id,
					basketCount
				}).then(res => {
					this.getShoppingCart()
				})
			}
			// let index = this.productSkuSpecifications.findIndex(item => item.skuKey == this.skuIds.join('/'))
			// this.productSkuSpecifications.splice(index, 1, this.skuInfo)
			// this.goodsSkuMap.set(this.goods.id, {
			// 	productSkus: this.productSkus,
			// 	productSkuSpecifications: this.productSkuSpecifications
			// })
		},
		close() {
			this.show = false
			this.skuInfo = {}
			this.goods = {}
			this.skuIds = []
			this.cartList = Array.from(this.checkGoodsMap.values())
		},
		delCartGoods (item,index) {
			this.cartList.splice(index,1)
			postDelStoreCartItem(item.skuId).then(res => {
				this.getShoppingCart()
			})
		},
		cartGoodsNumChange(goods, basketCount) {
			postEditStoreCart({
				skuId: goods.skuId,
				basketCount
			}).then(res => {
				this.getShoppingCart()
			})
		},
		cartPopupClose(isReset) {
			if (isReset && this.cartList.length > 0) {
				postDelStoreCart(this.storeId).then(res => {
					if (res.code === 200) {
						this.cartList = []
						this.getShoppingCart()
						this.$emit('close')
					}
				})
			} else {
				this.getShoppingCart()
				this.$emit('close')
			}
		},
		pay() {
			if (this.cartList.length) {
				this.$goTo('/pages/systemPay/nearby/store/previewOrder', { storeId: this.storeId})
			} else {
				this.$toast(this.$t('nearby.payErr'))
			}
		}
	}
}
</script>

<style lang="scss" scoped></style>
